const Base = require('./base.js');
const Config = require('./gameidleshopconfig.js');
const api_limit={time:30,count:2*60*60/30}//加入到新服务器

module.exports = class extends Base {

  apiLimit(time,count){//加入到新服务器
    const cur_time=this.getTime()
    return cur_time-time>api_limit.time&&count<=api_limit.count
  }
  /**
  * 登录获取信息 
  *  @return {Promise} []
  */
  async loginUpdataTimeAction() {
    // const wallet_address = this.post('wallet_address');
    const id = this.getLoginUserId();
    const user = await this.model('gameuser')
      .where({ id: id,isBan:0 })
      .find();

    const levelInfo = Config.levelJson[user.level - 1];

    //重新计算矿山的值hashrate，不会自动收获到cur_hashrate
    let newhashrate = user.hashrate;
    let newlimit_add_money = user.limit_add_money;
    let tempTime = parseInt(Date.now() / 1000) - user.last_login_time;
    let limit = parseInt(levelInfo.limit);

    if (newhashrate + tempTime < limit) {
      newhashrate += tempTime;
      newlimit_add_money = 0;
    } else {
      newhashrate = limit;
      newlimit_add_money = 1;
    }

    await this.model('gameuser')
      .where({ id: id })
      .update({

        hashrate: newhashrate,
        limit_add_money: newlimit_add_money,
        last_login_time: parseInt(Date.now() / 1000),
      });

    const records = await this.model('gameuser_record')
      .where({ id: id })
      .order(['recordtime DESC'])
      .select();

    return this.success({
      hashrate: user.hashrate,
      level: user.level,
      cur_hashrate: parseInt(user.cur_hashrate),
      limit_add_money: user.limit_add_money,
      nextlevelneed: levelInfo.nextlevelneed,
      limit: limit,
      underling_hashrate: parseInt(user.underling_hashrate),
      m_InvitationCode:user.m_InvitationCode,
      underling_limit:user.underling_limit,
      underling_count:user.underling_count,
    });
  };

  /**
  * 升级 用户的cur_hashrate（已经收获的矿）减去升级需求
  *  @return {Promise} []
  */
  async LevelUpAction() {
    // const wallet_address = this.post('wallet_address');

    const id = this.getLoginUserId();
    const user = await this.model('gameuser')
      .where({ id: id,isBan:0 })
      .find();

    if (think.isEmpty(user)) {
      return this.fail(8006, '账号输入有误');
    };

    if (user.level >= 0 && user.level <= 100) {
      let level = parseInt(user.level);
      let levelInfo = Config.levelJson[level - 1];
      let nextlevelneed = parseInt(levelInfo.nextlevelneed);

      if (user.cur_hashrate < nextlevelneed) {
        return this.fail(8004, '现有金币不足，升级失败');
      } else {
        await this.model('gameuser')
          .where({ id: id })
          .update({
            level: level + 1,
            cur_hashrate: parseInt(user.cur_hashrate) - nextlevelneed,
            underling_limit: 5 + level * 2
          });

        const user2 = await this.model('gameuser')
          .where({ id: id })
          .find();

        levelInfo = Config.levelJson[level];
        return this.success({
          level: user2.level,
          cur_hashrate: user2.cur_hashrate,
          limit_add_money: user2.limit_add_money,
          nextlevelneed: parseInt(levelInfo.nextlevelneed),
          limit: parseInt(levelInfo.limit),
          hashrate: user2.hashrate,
          underling_hashrate: parseInt(user2.underling_hashrate)
        });
      }
    } else {
      return this.fail(8005, '升级失败');
    }
  };

  /**
 * 客户端每5秒自动同步一次矿山的矿hashrate（不会自动收获）（心跳测试也是这个） 已经弃用
 *  @return {Promise} []
 */
  async updataTimeAction() {
    // const wallet_address = this.post('wallet_address');
    const id = this.getLoginUserId();
    const user = await this.model('gameuser')
      .where({ id: id })
      .find();

    //如果已经到上限，则只同步下属算力
    if (user.limit_add_money == 1) {
      return this.success({
        hashrate: user.hashrate,
        cur_hashrate: user.cur_hashrate,
        underling_hashrate: parseInt(user.underling_hashrate)
      });
    }
    const levelInfo = Config.levelJson[user.level - 1];

    //重新计算矿山的值hashrate，不会自动收获到cur_hashrate
    let newhashrate = parseInt(user.hashrate);
    let newlimit_add_money = user.limit_add_money;
    let tempTime = parseInt(Date.now() / 1000) - user.last_login_time;
    let limit = parseInt(levelInfo.limit);

    if (newhashrate + tempTime < limit) {
      newhashrate += tempTime;
      newlimit_add_money = 0;
    } else {
      newhashrate = limit;
      newlimit_add_money = 1;
    }

    await this.model('gameuser')
      .where({ id: id })
      .update({
        hashrate: newhashrate,
        limit_add_money: newlimit_add_money,
        last_login_time: parseInt(Date.now() / 1000),
      });

    return this.success({
      hashrate: user.hashrate,
      underling_hashrate: user.underling_hashrate
    });
  };


  /**
   * 带重新算钱的
  * 收获矿山的钱
  *  @return {Promise} []
  */
  async harvestAction() {//下次加
    // const wallet_address = this.post('wallet_address');
    const isNet=(this.ctx.state.rip=="");
    const token=this.post('harvest_token')||'';
    const id = this.getLoginUserId();
    const user = await this.model('gameuser')
      .where({ id: id,isBan:0 })
      .find();
    if (think.isEmpty(user)) {
      return this.fail(8006, '地址输入错误');
    };
    // const verify=await this.vcaptcha(token,user.wallet_address,!isNet?this.ctx.state.rip:this.ctx.ip,this.ctx.referer(true)!='h5.danghongfang.com'?3:4)
    // //console.log(verify)
    // if(!verify){
    //   return this.fail(8021,{zh:'验证未通过，请重试。',en:' verification failed, please try again later'})
    // }

    if(!think.isEmpty(user.havrest_time)){//加入
      if(!this.apiLimit(user.havrest_time,user.havrest_api_call_count)){
        // console.log(`${this.formtime(new Date(),"MM-dd hh:mm:ss")}-->(${user.wallet_address}):调用接口异常`)
        await this.model('gameuser')
            .where({wallet_address:user.wallet_address,isBan:0,day_activate:1})
            .increment('error_havrest',1)
        return this.fail(8007, '账号异常,请重新登陆');
      }
    }
    if (user.level >= 0 && user.level <= 100) {
      const levelInfo = Config.levelJson[user.level - 1];

      //重新计算算力的值
      let newhashrate = parseInt(user.hashrate);
      let newlimit_add_money = user.limit_add_money;
      let tempTime = parseInt(Date.now() / 1000) - user.last_login_time;
      let limit = parseInt(levelInfo.limit);

      if (newhashrate + tempTime < limit) {
        newhashrate += tempTime;
        newlimit_add_money = 0;
      } else {
        newhashrate = limit;
        newlimit_add_money = 1;
      }

      //玩家获取的算力计算5%，送给邀请人
      let temp5 = newhashrate * 5 / 100;

      const lead_user = await this.model('gameuser')
        .where({ m_InvitationCode: user.lead_InvitationCode })
        .find();

      await this.model('gameuser')
        .where({ m_InvitationCode: user.lead_InvitationCode })
        .update({
          underling_hashrate: parseInt(lead_user.underling_hashrate) + temp5
        });

      //如果有下属的钱一并收了，但是下属的钱不送上家 所以才在计算上家奖励之后
      if (user.underling_hashrate >= 1) {
        newhashrate += parseInt(user.underling_hashrate);
      }

      await this.model('gameuser')
        .where({ id: id })
        .update({
          cur_hashrate: parseInt(user.cur_hashrate) + newhashrate,
          day_add_money: parseInt(user.day_add_money) + newhashrate,
          underling_hashrate: 0,
          limit_add_money: 0,
          hashrate: 0,
          havrest_time:this.getTime(),
          last_login_time: parseInt(Date.now() / 1000),
          havrest_api_call_count:['exp','havrest_api_call_count+1']
        });

      return this.success({
        cur_hashrate: parseInt(user.cur_hashrate) + newhashrate
      });
    } else {
      return this.fail(8007, '收获失败');
    };
  };

    /**
* 每天对所有当天激活过的用户做一次记录
*  @return {Promise} []
*/
  async resetDay5DataAction() {
      const password=this.post('reset_password')||'';

      console.log(this.formtime(new Date() ,"hh:mm"))

      if( password!=="Ssmartx" && (this.formtime(new Date() ,"hh:mm")!=="16:04"))
      {
        console.log("false")
        return false;
      }

    const today= (new Date(new Date().toLocaleDateString()).getTime());
      // console.log("today="+today);
      // console.log(new Date().toLocaleDateString());
    const yesterday= today-24*60*60*1000;
      // console.log(this.formtime(new Date(yesterday),"yyyy-MM-dd"))
    const unders = await this.model('gameuser')
      .where({ day_activate: 1,
        last_login_time:['>=',yesterday/1000],
      isBan:0,})
      .select();
      let m_day_add_Total = 0;
      console.log(JSON.stringify(unders))
    if (unders && unders.length > 0) {
    	unders.map((v)=>{m_day_add_Total += parseInt(v.day_add_money);});
    	let records=unders.map((v)=>{
          console.log(m_day_add_Total);
          console.log(v.day_add_money);
    		let curDay_SAT=parseFloat(v.day_add_money) / parseFloat(m_day_add_Total) * Config.provideSAT;
          console.log(curDay_SAT);
    		if(curDay_SAT>50000){
    			curDay_SAT=50000;
    		}
    	return	{
    			wallet_address: v.wallet_address,
    		    recordtime: this.formtime(new Date(yesterday),"yyyy-MM-dd"),
        		SATrecord: curDay_SAT,
        		last_login_ip: v.last_login_ip,
        		curDay_SAT: v.day_add_money
    		}
    	});
      await this.model('gameuser_record').addMany(records);
      console.log("records")
      let dates=unders.map((v)=>{
    	return	{
    	        id: v.id,
          		day_add_money: 0,
          		day_activate: 0,
          		havrest_api_call_count:0,
          		automatic_bonus_time:0,
          		warn_account:'正常',
          		underline_active:0,
          		error_havrest:0
    		}
      });
      await this.model('gameuser').updateMany(dates);
    }
      await this.model('gameuser_statistics').add({
      DAU: unders.length,
      date: parseInt(new Date().getTime()) - 600000,
      hashrateTotal: m_day_add_Total
    });
  };

  /**
* 每天新建一个记录实时的统计字段
*  @return {Promise} []
*/
  async createStatisticalAction() {
    await this.model('gameuser_realTime_statistics').add({
      DAU_realTime: 0,
      date: (new Date(new Date().toLocaleDateString()).getTime()) / 1000
    });
  };

  /**
* 重新计算下属数目
*  @return {Promise} []
*/
  async checkoutUnderling_countAction() {
    const unders = await this.model('gameuser')
      .where()
      .select();

    for (let index = 0; index < unders.length; index++) {
      let number = await this.model('gameuser')
        .where({ lead_InvitationCode: unders[index].m_InvitationCode })
        .select();
      await this.model('gameuser')
        .where({ wallet_address: unders[index].wallet_address })
        .update({
          underling_count: number.length,
        });
    }
  };

    /**
* 重新计算下属限制数目
*  @return {Promise} []
*/
async checkoutUnderlingLimitAction() {
  const unders = await this.model('gameuser')
    .where()
    .select();

  let underlingLimits=unders.map((v)=>{
    return {
      id:v.id,
      underling_limit: parseInt(v.level)*2+5,
    }
  });

  this.model('gameuser').updateMany(underlingLimits);
};

  /**
* 获取记录信息 正常为登录获取信息时获取
*  @return {Promise} []
*/
  async getRecordedInfoAction() {
    // const wallet_address = this.post('wallet_address');
    const id = this.getLoginUserId();
    const user = await this.model('gameuser')
        .where({ id: id,isBan:0 })
        .find();
    const records = await this.model('gameuser_record')
      .where({ wallet_address: user.wallet_address })
      .order(['recordtime DESC'])
      .select();
    return this.success({
      record: records
    });
  };
}

